//
//  SYS_MessageVC.m
//  System_App
//
//  Created by czy001 on 2017/11/27.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageVC.h"
#import "SYS_LoginVC.h"
#import "ChatViewController.h"
#import "SYS_TitleAndImageView.h"
#import "SYS_MemberModel.h"
#import "SYS_MemberDetailVC.h"
#import "SYS_MessageStoreListVC.h"
#import "SYS_MessageSendSearchVC.h"

@interface SYS_MessageVC ()
{
    dispatch_queue_t refreshQueue;
    
    UIView *bjView;//背景视图
    UILabel *alertLabel;//环信连接状态
    UIView *lineView;
}

@property (nonatomic, copy) NSMutableArray *dataArray;

@end

@implementation SYS_MessageVC

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (id)init
{
    self=[super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAndSortView) name:@"REFRESHMESSAGE" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewDidTriggerHeaderRefresh) name:@"RELOADMESSAGE" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGEMESSAGETAB" object:@(selectIndex)];
        
        _dataArray=[NSMutableArray array];
        _leftVC=[[SYS_MessageHomeVC alloc] init];
        _rightVC=[[SYS_MessageContactVC alloc] init];

        [self registerNotifications];
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([[EMClient sharedClient] isLoggedIn]) {
//        [self tableViewDidTriggerHeaderRefresh];
    }
    else
    {
        [self loginWithUsername:[SYS_LoginModel instance].admin.imKey password:[SYS_LoginModel instance].admin.imPasswd];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //    [self unregisterNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=RGBACOLOR(242, 242, 242, 1);
    self.edgesForExtendedLayout = UIRectEdgeNone;
    selectIndex=0;
    [self viewDisplay];
    
    [self tableViewDidTriggerHeaderRefresh];
}

- (void)viewDisplay
{
    bjView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
    bjView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bjView];
    
    NSArray *array=[NSArray arrayWithObjects:@"消息",@"通讯录", nil];
    for (int i=0; i<[array count]; i++) {
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame=CGRectMake(40+(SCREENWIDTH-80)/2*i, 0, (SCREENWIDTH-80)/2, 38);
        [button setTitle:array[i] forState:0];
        [button setTitleColor:DGHColor(30, 30, 30) forState:UIControlStateNormal];
        [button setTitleColor:MainColor forState:UIControlStateSelected];
        button.titleLabel.font=[UIFont fontWithName:@"PingFangSC-Regular" size:14];
        button.tag=800+i;
        if (i==selectIndex) {
            button.selected = YES;
        }
        [button addTarget:self action:@selector(buttonClickChange:) forControlEvents:UIControlEventTouchUpInside];
        
        [bjView addSubview:button];
    }
    float width=((SCREENWIDTH-80)/2-70)/2+40;
    lineView=[[UIView alloc]initWithFrame:CGRectMake(width, 39, 70, 1.5)];
    lineView.backgroundColor=MainColor;
    [bjView addSubview:lineView];
    
    _operation=[[DSDataBaseOperation alloc] init];
    
    alertLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 25)];
    alertLabel.textColor=[UIColor whiteColor];
    alertLabel.textColor=RGBACOLOR(255, 122, 16, 1);
    alertLabel.backgroundColor=RGBACOLOR(255, 212, 143, 1);
    alertLabel.text=@"   连接环信服务器失败";
    alertLabel.font=[UIFont systemFontOfSize:13];
    //    alertLabel.hidden=[[EMClient sharedClient] isLoggedIn];
    [self.view addSubview:alertLabel];
    
    //调整主界面位置
    [self adjustScrollViewLocation];
    
    _mainScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(bjView.frame)+5, SCREENWIDTH, SCREENHEIGHT-40-NavBarHeight-TabBarHeight)];
    _mainScrollView.showsVerticalScrollIndicator=NO;
    _mainScrollView.showsHorizontalScrollIndicator=NO;
    _mainScrollView.scrollEnabled=NO;
    [self.view addSubview:_mainScrollView];
    
    _leftVC.view.frame=CGRectMake(0, 0, SCREENWIDTH, _mainScrollView.frame.size.height);
    _leftVC.delegate0=self;
    //    _leftVC.dataArr=_dataArray;
    [_mainScrollView addSubview:_leftVC.view];
    
    _rightVC.view.frame=CGRectMake(SCREENWIDTH, 0, SCREENWIDTH, _mainScrollView.frame.size.height);
    _rightVC.delegate=self;
    [_mainScrollView addSubview:_rightVC.view];
    
    _mainScrollView.contentSize=CGSizeMake(SCREENWIDTH*2, _mainScrollView.frame.size.height);
}

//调整主界面位置
- (void)adjustScrollViewLocation
{
    if (![[EMClient sharedClient] isLoggedIn]) {
        alertLabel.hidden=NO;
        
        bjView.frame=CGRectMake(0, 25, SCREENWIDTH, 40);
        _mainScrollView.frame=CGRectMake(0, CGRectGetMaxY(bjView.frame)+5+25, SCREENWIDTH, SCREENHEIGHT-45-NavBarHeight-TabBarHeight-25);
    }
    else
    {
        alertLabel.hidden=YES;
        
        bjView.frame=CGRectMake(0, 0, SCREENWIDTH, 40);
        _mainScrollView.frame=CGRectMake(0, CGRectGetMaxY(bjView.frame)+5, SCREENWIDTH, SCREENHEIGHT-45-NavBarHeight-TabBarHeight);
    }
}


- (void)buttonClickChange:(UIButton *)button
{
    
    UIButton *btn = (UIButton *)[self.view viewWithTag:selectIndex+800];
    btn.selected = NO;
    [btn setTitleColor:DGHColor(30, 30, 30) forState:UIControlStateNormal];
    
    selectIndex=button.tag-800;
    
    UIButton *currentSelectBtn = (UIButton *)[self.view viewWithTag:button.tag];
    currentSelectBtn.selected = YES;

    float width=((SCREENWIDTH-80)/2-70)/2+40;
    CGRect rect = lineView.frame;
    rect.origin.x = selectIndex * (70+((SCREENWIDTH-80)/2-70))+width;
    [UIView animateWithDuration:0.3 animations:^{
        lineView.frame = rect;
    }];
    [_mainScrollView setContentOffset:CGPointMake(SCREENWIDTH*selectIndex, 0) animated:YES];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGEMESSAGETAB" object:@(selectIndex)];
}

- (void)searchBarDidClickToSearch
{
//    DGHSearchResultViewController *vc=[[DGHSearchResultViewController alloc] init];
//    vc.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
//    DGHNavigationController *nav=[[DGHNavigationController alloc] initWithRootViewController:vc];
//    //    nav.navigationBarHidden=YES;
//    [self presentViewController:nav animated:YES completion:nil];
}

#pragma UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self searchBarDidClickToSearch];
    return NO;
}

#pragma DGHMessageHomeViewControllerDelegate
- (void)didSelectSectionTwoOfModel:(id<IConversationModel>)model
{
    EMConversation *conversation = model.conversation;
    if (conversation) {
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
        DGHUserInfo *info=[_operation searchUserInfoWithHXName:model.conversation.conversationId];
        if (info.isServer.intValue ==1) {
            chatController.isServer=YES;
        }
        if (conversation.type == EMConversationTypeChat) {
            if (info.username) {
                chatController.title = info.username;
            }
            else
            {
                chatController.title = conversation.conversationId;
            }
        }
        else
        {
            chatController.title=[conversation.ext objectForKey:@"subject"];
        }
        [self.navigationController pushViewController:chatController animated:YES];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
    }
}

#pragma DGHGroupListViewControllerDelegate
- (void)didSelectGroup:(EMGroup *)group
{
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:group.groupId conversationType:EMConversationTypeGroupChat];
    
    chatController.title = group.subject;
    [self.navigationController pushViewController:chatController animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
}


#pragma mark SYS_MessageContactVCDelegate
- (void)didSelectMember:(SYS_MemberModel *)model
{
    SYS_MemberDetailVC *vc=[[SYS_MemberDetailVC alloc] init];
    vc.userId=model.userId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)goStoreList
{
    SYS_MessageStoreListVC *vc=[[SYS_MessageStoreListVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didSelectMemberToChat:(SYS_MemberModel *)model
{
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:model.imKey conversationType:EMConversationTypeChat];
    DGHUserInfo *info=[_operation searchUserInfoWithHXName:model.imKey];
    if (info.username.length>0) {
        chatController.title = info.username;
    }
    else
    {
        chatController.title = model.nickName;
    }
    [self.navigationController pushViewController:chatController animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
}

- (void)goSearchMember
{
    SYS_MessageSendSearchVC *vc=[[SYS_MessageSendSearchVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 返回一张纯色图片
/** 返回一张纯色图片 */
- (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark - data

-(void)refreshAndSortView
{
    __weak typeof(self) weakself = self;
    if (!refreshQueue) {
        refreshQueue = dispatch_queue_create("com.easemob.conversation.refresh", DISPATCH_QUEUE_SERIAL);
    }
    dispatch_async(refreshQueue, ^{
        if ([weakself.dataArray count] > 0) {
            if ([[weakself.dataArray objectAtIndex:0] isKindOfClass:[EaseConversationModel class]]) {
                NSArray* sorted = [weakself.dataArray sortedArrayUsingComparator:
                                   ^(EaseConversationModel *obj1, EaseConversationModel* obj2){
                                       EMMessage *message1 = [obj1.conversation latestMessage];
                                       EMMessage *message2 = [obj2.conversation latestMessage];
                                       if(message1.timestamp > message2.timestamp) {
                                           return(NSComparisonResult)NSOrderedAscending;
                                       }else {
                                           return(NSComparisonResult)NSOrderedDescending;
                                       }
                                   }];
                [weakself.dataArray removeAllObjects];
                [weakself.dataArray addObjectsFromArray:sorted];
            }
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"MESSAGEDATA" object:weakself.dataArray];
            [self tableViewDidTriggerHeaderRefresh];
        });
        
    });
}

- (void)tableViewDidTriggerHeaderRefresh
{
    __weak typeof(self) weakself = self;
    if (!refreshQueue) {
        refreshQueue = dispatch_queue_create("com.easemob.conversation.refresh", DISPATCH_QUEUE_SERIAL);
    }
    dispatch_async(refreshQueue, ^{
        
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        NSArray* sorted = [conversations sortedArrayUsingComparator:
                           ^(EMConversation *obj1, EMConversation* obj2){
                               EMMessage *message1 = [obj1 latestMessage];
                               EMMessage *message2 = [obj2 latestMessage];
                               if(message1.timestamp > message2.timestamp) {
                                   return(NSComparisonResult)NSOrderedAscending;
                               }else {
                                   return(NSComparisonResult)NSOrderedDescending;
                               }
                           }];
        
        
        NSLog(@"-----%@",weakself.dataArray);
        //        if (sorted.count>0) {
        [weakself.dataArray removeAllObjects];
        //        }
        
        for (EMConversation *converstion in sorted) {
            EaseConversationModel *model = nil;
            model = [[EaseConversationModel alloc] initWithConversation:converstion];
            
            if (model) {
                [weakself.dataArray addObject:model];
            }
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"MESSAGEDATA" object:weakself.dataArray];
        });
    });
}

#pragma mark - registerNotifications
-(void)registerNotifications{
    [self unregisterNotifications];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
    [[EMClient sharedClient].chatManager removeDelegate:self];
    [[EMClient sharedClient].groupManager removeDelegate:self];
}


#pragma mark --懒加载
- (NSMutableArray *)dataArr
{
    if (_dataArray == nil) {
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //    [self showHudInView:self.view hint:@"登录中..."];
    //异步登陆账号
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself hideHud];
            if (!error) {
                //设置是否自动登录
                [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"STATUS"];
                
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                //获取数据库中数据
                [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient] migrateDatabaseToLatestSDK];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
                        [[ChatDemoHelper shareHelper] asyncConversationFromDB];
                        [[ChatDemoHelper shareHelper] asyncPushOptions];
                        [MBProgressHUD hideAllHUDsForView:weakself.view animated:YES];
                        
                        //调整主界面位置
                        [self adjustScrollViewLocation];
                        
                        [self tableViewDidTriggerHeaderRefresh];
                        
                        //保存最近一次登录用户名
                        [weakself saveLastLoginUsername];
                    });
                });
            }
            else
            {
                //调整主界面位置
                [self adjustScrollViewLocation];
            }
        });
    });
}

#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[EMClient sharedClient] currentUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
        [ud synchronize];
    }
}

- (NSString*)lastLoginUsername
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
    if (username && username.length > 0) {
        return username;
    }
    return nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
